package com.specter.utils;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

import jakarta.servlet.http.HttpServletResponse;

/**
 * Note:http操作工具类
 * 
 * @author Liang.Wang
 * @version 2017-04-12
 */
public abstract class HttpUtils {

	public static final String CONTENT_TYPE_TEXT = "text/plain";
	public static final String CONTENT_TYPE_HTML = "text/html";
	public static final String CONTENT_TYPE_XML = "text/xml";
	public static final String CONTENT_TYPE_JSON = "application/json";

	private HttpUtils() {
	}

	/**
	 * 给客户端输出相应的内容
	 * 
	 * @param response
	 * @param contentType
	 * @param content
	 */
	public static void render(HttpServletResponse response, String contentType, String content) {
		response.setContentType(contentType + ";charset=UTF-8");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		try {
			response.getWriter().write(content);
			response.getWriter().flush();
			response.getWriter().close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static String get(String uri) {
		StringBuilder result = new StringBuilder();
		try {
			URL url = new URL(uri);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("GET");

			BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));

			String line = "";
			while ((line = br.readLine()) != null) {
				result.append(line).append("\n");
			}

			br.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result.toString();
	}

	public static String post(String uri, Object data) {
		StringBuilder result = new StringBuilder();
		try {
			URL url = new URL(uri);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();

			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setUseCaches(false);
			connection.setRequestMethod("POST");
			// 设置请求属性
			connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			connection.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
			connection.setRequestProperty("Charset", "UTF-8");
			connection.connect();// 连接,也可以不用明文connect，使用下面的httpConn.getOutputStream()会自动connect

			// 构造输入参数，支持POJO/MAP/JSON
			Map<String, Object> map = null;
			if (data instanceof String) {
				map = JSONUtils.json2bean(data.toString());
			} else {
				map = BeanUtils.obj2Map(data);
			}
			StringBuilder sb = new StringBuilder();
			for (Map.Entry<String, Object> entry : map.entrySet()) {
				if (sb.length() != 0) {
					sb.append("&");
				}
				sb.append(entry.getKey());
				sb.append("=");
				sb.append(URLEncoder.encode(entry.getValue() + "", "UTF-8"));
			}
			// 建立输入流，向指向的URL传入参数
			DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
			dos.writeBytes(sb.toString());
			dos.flush();

			BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
			String line = "";
			while ((line = br.readLine()) != null) {
				result.append(line).append("\n");
			}

			br.close();
			dos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result.toString();
	}

	/**
	 * 客户端导出文件
	 * 
	 * @param response
	 * @param file
	 */
	public static void exp(HttpServletResponse response, java.io.File file) {
		try {
			// 获得文件的长度
			long filesize = file.length();
			response.reset();
			// 设置输出格式
			response.addHeader("content-type", "application/x-msdownload;");
			response.addHeader("Content-Disposition",
					"attachment;filename=" + java.net.URLEncoder.encode(file.getName(), "UTF-8"));
			response.addHeader("content-length", Long.toString(filesize));

			// 向客户端写入文件
			java.io.FileInputStream fin = new java.io.FileInputStream(file);
			byte[] b = new byte[4096];// 设置下载文件大小；
			jakarta.servlet.ServletOutputStream sos = response.getOutputStream();

			while (fin.read(b) > 0) {
				sos.write(b);
			}

			sos.flush();
			fin.close();
			file.delete();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static String upload(String uri, java.io.File file) {
		String end = "\r\n";
		String twoHyphens = "--";
		String boundary = "*****";

		StringBuilder result = new StringBuilder();
		try {
			URL url = new URL(uri);

			HttpURLConnection connection = (HttpURLConnection) url.openConnection();// http的连接类
			connection.setDoInput(true);// 设置是否读入，默认情况下是true;
			connection.setDoOutput(true);// 设置是否输出
			connection.setUseCaches(false);// Post 请求不能使用缓存
			connection.setRequestMethod("POST");// 设定请求的方法，默认是GET
			connection.setRequestProperty("Connection", "Keep-Alive");// 设置字符编码连接参数
			connection.setRequestProperty("Charset", "UTF-8");// 设置字符编码
			connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);// 设置请求内容类型

			// 设置DataOutputStream
			DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
			dos.writeBytes(twoHyphens + boundary + end);
			dos.writeBytes(
					"Content-Disposition:form-data; " + "name=\"file\";filename=\"" + file.getName() + "\"" + end);
			dos.writeBytes(end);

			FileInputStream fis = new FileInputStream(file);
			int bufferSize = 1024;
			byte[] buffer = new byte[bufferSize];
			int length = -1;
			while ((length = fis.read(buffer)) != -1) {
				dos.write(buffer, 0, length);
			}
			dos.writeBytes(end);
			dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
			dos.flush();/* close streams */
			fis.close();/* close streams */

			if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
				BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
				String line = null;
				while ((line = br.readLine()) != null) {
					result.append(line).append("\n");
					result.append("\n");
				}
				br.close();
			} else if (connection.getResponseCode() >= 300) {
				throw new Exception("HTTP Request is not success, Response code is " + connection.getResponseCode());
			}

			dos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result.toString();
	}

	public static File download(String uri, String dir) {
		File file = null;
		try {
			URL url = new URL(uri);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("POST");// 设定请求的方法，默认是GET
			connection.setRequestProperty("Charset", "UTF-8");// 设置字符编码
			connection.connect();

			int length = connection.getContentLength();// 文件大小

			String filePathUrl = connection.getURL().getFile();// 文件名
			String fileFullName = filePathUrl.substring(filePathUrl.lastIndexOf(File.separatorChar) + 1);

			BufferedInputStream bin = new BufferedInputStream(connection.getInputStream());

			String path = dir + File.separatorChar + fileFullName;
			file = new File(path);
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			FileOutputStream out = new FileOutputStream(file);
			int size = 0, len = 0;
			byte[] buf = new byte[1024];
			System.out.print("下载进度：");
			while ((size = bin.read(buf)) != -1) {
				len += size;
				out.write(buf, 0, size);
				System.out.print(">>" + len * 100 / length + "%");
			}
			bin.close();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return file;
	}

}
